'''

    main window tests

'''
import sys
from PyQt4 import QtGui, QtOpenGL, QtCore, Qt

import rsc

import gv
import graph_data
import graph_items

import viewFactory

class DockTitleBar( QtGui.QWidget ):
    def __init__( self, dock ):
        QtGui.QWidget.__init__( self )
        
        lo = QtGui.QBoxLayout( QtGui.QBoxLayout.LeftToRight, self )
        
        select = QtGui.QToolButton(self)
        select.setIcon( rsc.GetIcon( 'ink' ) )
        select.setMenu( viewFactory.GetCreateMenu(self, self.SetViewType) )
        select.setPopupMode( QtGui.QToolButton.InstantPopup )
        
        close = QtGui.QToolButton(self)
        closeAction = QtGui.QAction( rsc.GetIcon( 'clear' ), 'Close', close )
        closeAction.setToolTip("Close this panel")
        closeAction.setStatusTip("Close this panel")
        self.connect(
            closeAction, QtCore.SIGNAL( "triggered(QAction*)"), self.OnTriggered
        )
        close.setDefaultAction(closeAction)
        self.connect(
            close, QtCore.SIGNAL( "triggered(QAction*)"), self.OnTriggered
        )
        
        lo.addWidget( select )
        lo.addStretch( 100 )
        lo.addWidget( close )
        
        self.setLayout( lo )
    
    def resize( self, *args ):
        QtGui.QWidget.resize( self, *args )
        self.setMinimumSize( *args )
    
    def minimumSizeHint( self ):
        return QtCore.QSize( 16, 16 )
    
    def GetDock(self):
        return self.parentWidget()
    
    def OnTriggered( self, action ):
        dock = self.GetDock()
        if action.text() == 'Close':
            dock.parentWidget().removeDockWidget( dock )
            return
    
    def SetViewType( self, viewType ):
        view = viewFactory.CreateView( viewType, None )
        #view.setStyleSheet( "* { background-color: #FF8800 } " )
        view.setMinimumSize( 16, 16 )
        self.GetDock().setWidget(view)
        self.GetDock().setWindowTitle( viewType )
        
    def OnClose(self):
        print 'close'
        
class AppWin( QtGui.QMainWindow ):
    def __init__( self, *args ):
        QtGui.QMainWindow.__init__( self, *args )
        
        self.resize( 800, 600 )
        self.docks = []
        self.unmaxdata = None
        
        center = QtGui.QWidget(self)
        self.setCentralWidget( center )
        self.setDockNestingEnabled( True )
        self.setDockOptions(
            QtGui.QMainWindow.VerticalTabs
        )
        
        # create tabs
        self.ctxTabs = QtGui.QTabBar( center )
        self.ctxTabs.contextMenuEvent = self.tabsContextMenuEvent
        self.scenes = []
        self.items = []
        for ctx in (1,2,3,4):
            self.ctxTabs.addTab( 'Context #'+str(ctx) )
            scene = graph_items.Scene()
            root = QtGui.QGraphicsItemGroup()
            scene.setRoot( root )
            self.LoadGraph( scene )
            self.scenes.append( scene )
            
        # create main view
        self.view = gv.GV( center )
        self.view.setFocus()
        
        # status bar
        status = self.statusBar()
        status.setSizeGripEnabled(False)
        statuslabel = QtGui.QLabel()
        statuslabel.setFrameStyle(QtGui.QFrame.StyledPanel|QtGui.QFrame.Sunken)
        status.addPermanentWidget(statuslabel)
        status.showMessage("Generic UI test")
        
        # Menu bar
        sessionMenu = self.menuBar().addMenu("&Session")
        sessionMenu.addAction( "&Restore", self.RestoreSession )
        sessionMenu.addAction( "&Save", self.SaveSession )
        sessionMenu.addAction( "&Quit", self.close )
        
        viewMenu = self.menuBar().addMenu("Views")
        viewMenu.addAction( "Add View", self.AddView )
        viewMenu.addAction( "Add Shell", self.AddShell )
        
        # toolbar
        mainTB = self.addToolBar( "App" )
        mainTB.setObjectName( "AppToolBar" )
        mainTB.addAction( "Add View", self.AddView )
        mainTB.addAction( "Add Shell", self.AddShell )
        
        # layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.ctxTabs)
        layout.addWidget(self.view)
        center.setLayout(layout)
        
        # connections
        self.connect( self.ctxTabs, QtCore.SIGNAL( "currentChanged(int)"), self.OnTabChange )
        self.OnTabChange( 0 )
        
        # restore 
        self.RestoreSession()
    
    def _ClearDocks( self ):
        for d in self.docks:
            self.removeDockWidget(d)
            d.destroy()
        self.docks = []
    
    def _AddViewDock( self, title, name=None ):
        dock = QtGui.QDockWidget( title )
        self.docks.append( dock )
        
        if name is None:
            name = 'Dock_'+str(len(self.docks))
        dock.setObjectName( name )
        dock.setFeatures(
            QtGui.QDockWidget.AllDockWidgetFeatures
            #| QtGui.QDockWidget.DockWidgetVerticalTitleBar
        )
        dock.setAllowedAreas(
            QtCore.Qt.RightDockWidgetArea
            | QtCore.Qt.LeftDockWidgetArea
            | QtCore.Qt.TopDockWidgetArea
            | QtCore.Qt.BottomDockWidgetArea
        )
        
        t = DockTitleBar( dock )
        dock.setTitleBarWidget( t )
        t.SetViewType( title )
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)
        return dock
    
    def AddView( self, type=None ):
        if not type:
            type = '???'
        dock = self._AddViewDock( type )
        return dock
    
    def AddShell( self ):
        dock = self._AddViewDock( 'Shell' )
        process.write("cd /u/mgl")
        return dock
    
    def SaveSession( self ):
        settings = QtCore.QSettings("MGL", "MainWinTest")
        settings.clear()
        settings.setValue("pos", QtCore.QVariant(self.pos()))
        settings.setValue("size", QtCore.QVariant(self.size()))
        
        dockTitles = QtCore.QStringList([d.windowTitle() for d in self.docks])
        settings.setValue("dockTitles", QtCore.QVariant(dockTitles) )
        
        dockNames = QtCore.QStringList([d.objectName() for d in self.docks])
        settings.setValue("dockNames", QtCore.QVariant(dockNames) )
        
        loData = self.saveState( 1 )
        settings.setValue("layout", QtCore.QVariant(loData) )
    
    def RestoreSession( self ):
        settings = QtCore.QSettings("MGL", "MainWinTest");
        pos = settings.value("pos", QtCore.QVariant(QtCore.QPoint(200, 200))).toPoint()
        size = settings.value("size", QtCore.QVariant(QtCore.QSize(400, 400))).toSize()
        
        self.resize(size)
        self.move(pos)
        
        dockTitles = settings.value("dockTitles" ).toStringList()
        dockNames = settings.value("dockNames").toStringList()
        self._ClearDocks()
        [ self._AddViewDock(t,name=n) for t,n in zip(dockTitles,dockNames) ]
        loData = settings.value("layout")
        if loData:
            ok = self.restoreState( loData.toByteArray(), 1 )
        self.setDockNestingEnabled( True )
        return ok
    
    def LoadGraph( self, scene ):
        graph = graph_data.BIG
        idToItem = {}
        for id, pos in graph[0].iteritems():
            item = graph_items.AssetItem( self, pos[0], pos[1], 'Item '+str(id) )
            idToItem[id] = item
            scene.addItem(item)
        print 'Created', len( graph[0] ), 'items'
        
        for src, dst, ltype in graph[1]:
            link = graph_items.LinkItem( idToItem[src], idToItem[dst], ltype )
            scene.addItem(link)
        print 'Created', len( graph[1] ), 'links'
        scene.setSceneRect( scene.sceneRect().adjusted(20,20,20,20) )
    
    def OnTabChange( self, index ):
        self.view.setScene( self.scenes[index] )
        color = (
            None,
            '#8888FF',
            '#88FF88',
            '#FF8888',
            '#FF88FF',
        )[index]
        if color:
            self.setStyleSheet( "* { background-color: "+color+" } " )
        else:
            self.setStyleSheet( "" )
    
    def tabsContextMenuEvent(self, event):
        menu = QtGui.QMenu(self)
        tm = menu.addAction("Toggle Maximize")
        ab = menu.addAction("Hop")
        action = menu.exec_(self.ctxTabs.mapToGlobal(event.pos()))
        if action == tm:
            print 'Max'
            if self.unmaxdata is None:
                self.unmaxdata = self.saveState( 1 )
                [ d.hide() for d in self.docks ]
            else:
                self.restoreState( self.unmaxdata, 1 )
                self.unmaxdata = None
        elif action == ab:
            print 'Hop'

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    
    w = AppWin()
    w.show()
    
    ret = app.exec_()
    sys.exit(ret)
